from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from typing import List, Optional

from src.schemas.question import (
    Question, QuestionCreate, QuestionUpdate
)
from src.dao import question_crud   # 导入CRUD操作
from src.database.database import get_async_db, get_sync_db  # 数据库依赖
from src.schemas.question import QuestionType  # 题型枚举

# 创建路由实例（定义API前缀和标签）
router = APIRouter(
    prefix="/src/v1/questions",  # API路径前缀
    tags=["试卷管理模块"]  # 在Swagger文档中分类的标签
)
#
# # 初始化Dify客户端（单例）
# dify_client = DifyClient()
#
# @router.post("/generate",
#              response_model=QuestionGenerateResponse,
#              status_code=status.HTTP_201_CREATED)
# async def generate_questions(
#         request: QuestionGenerateRequest,
#         db: AsyncSession = Depends(get_async_db),
#         created_by: str = Query("AI", description="创建人标识（如用户名或'AI'）")
# ):
#     """
#     AI生成题目接口
#
#     根据教学大纲和参数，调用Dify生成题目并保存到数据库
#     """
#     try:
#         # 1. 调用Dify生成题目
#         generated_questions = dify_client.generate_questions(
#             outline=request.outline,
#             question_types=request.question_types,
#             counts=request.counts,
#             difficulty_range=request.difficulty_range,
#             major=request.major,
#             course=request.course
#         )
#
#         # 2. 批量保存到数据库（异步操作）
#         saved_questions = await question_crud.batch_create_questions_async(
#             db=db,
#             questions=generated_questions,
#             created_by=created_by
#         )
#
#         # 3. 返回结果
#         return {
#             "question_set_id": str(uuid.uuid4()),  # 生成唯一题目集ID
#             "total_count": len(saved_questions),
#             "questions": saved_questions
#         }
#
#     except Exception as e:
#         # 捕获所有异常，返回友好错误信息
#         raise HTTPException(
#             status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
#             detail=f"生成题目失败: {str(e)}"
#         ) from e


@router.post(
    "/generate",
    response_model=List[Question],
    status_code=status.HTTP_201_CREATED,
    summary="批量创建题目信息"
)
def batch_create_question_route(
        question: List[QuestionCreate],
        db: Session = Depends(get_sync_db),
        created_by: str = Query(..., description="创建人（手动录入必须指定用户名）")
):
    """手动创建题目接口（教师录入题目时使用）"""
    return question_crud.batch_create_questions(
        db=db,
        questions=question,
        created_by=created_by
    )


@router.post(
    "",
    response_model=Question,
    status_code=status.HTTP_201_CREATED,
    summary="手动创建题目信息"
)
def create_question_route(
        question: QuestionCreate,
        db: Session = Depends(get_sync_db),
        created_by: str = Query(..., description="创建人（手动录入必须指定用户名）")
):
    """手动创建题目接口（教师录入题目时使用）"""
    return question_crud.create_question(
        db=db,
        question=question,
        created_by=created_by
    )


@router.get(
    "/{question_id}",
    response_model=Question,
    summary="查询单个题目信息"
)
def get_question_route(
        question_id: int,
        db: Session = Depends(get_sync_db)
):
    """查询单个题目详情（按ID）"""
    db_question = question_crud.get_question(
        db=db, question_id=question_id
    )
    if db_question is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"题目ID {question_id} 不存在"
        )
    return db_question


@router.get("", response_model=List[Question], summary="模糊查询题目信息")
async def get_questions_route(
        skip: int = Query(0, ge=0, description="分页起始位置（从0开始）"),
        limit: int = Query(100, ge=1, le=1000, description="每页最大数量（1-1000）"),
        question_type: Optional[QuestionType] = Query(None, description=f"题型筛选，允许值：{[t for t in QuestionType]}"),
        course: Optional[str] = Query(None, description="按课程筛选（如'Python编程'）"),
        difficulty_min: Optional[float] = Query(None, ge=0, le=5, description="最小难度（0-5）"),
        difficulty_max: Optional[float] = Query(None, ge=0, le=5, description="最大难度（0-5）"),
        search_keyword: Optional[str] = Query(None, description="搜索关键词（匹配题目内容）"),
        db: Session = Depends(get_sync_db)
):
    """查询题目列表（支持多条件筛选和分页）"""
    # 验证题型参数（如果提供）
    q_type: Optional[QuestionType] = None
    if question_type:
        if question_type not in QuestionType.__args__:  # 检查是否为有效题型
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"无效的题型: {question_type}，允许的值: {[t for t in QuestionType]}"
            )
        q_type = question_type

    # 调用CRUD查询
    return  question_crud.get_questions(
        db=db,
        skip=skip,
        limit=limit,
        question_type=q_type,
        course=course,
        difficulty_min=difficulty_min,
        difficulty_max=difficulty_max,
        search_keyword=search_keyword
    )


@router.put("/{question_id}", response_model=Question, summary="更新题目信息")
def update_question_router(
        question_id: int,
        question: QuestionUpdate,
        db: Session = Depends(get_sync_db)
):
    """更新题目信息接口"""
    updated_question = question_crud.update_question(
        db=db,
        question_id=question_id,
        question_update=question
    )
    if updated_question is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"题目ID {question_id} 不存在"
        )
    return updated_question


@router.delete(
    "/{question_id}",
    status_code=status.HTTP_204_NO_CONTENT,
    summary="删除题目信息"
)
def delete_question_router(
        question_id: int,
        db: Session = Depends(get_sync_db)
):
    """删除题目接口（谨慎使用，会永久删除数据）"""
    success = question_crud.delete_question(db=db, question_id=question_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"题目ID {question_id} 不存在"
        )
    # 204状态码无返回内容
    return None
